package com.sirui.x.account.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sirui.x.account.entity.AccountInfoEntity;
import com.sirui.x.account.mapper.AccountInfoMapper;

@RestController
@RequestMapping("account")
public class AccountController {

	@Autowired
	private AccountInfoMapper accountInfoMapper;

	@RequestMapping("pay")
	public String pay() {

		return "account pay";
	}

	@RequestMapping("testdb")
	public String testdb() {
		AccountInfoEntity exist = accountInfoMapper
				.selectOne(Wrappers.<AccountInfoEntity>lambdaQuery().eq(AccountInfoEntity::getUserId, "10001"));

		AccountInfoEntity entity = new AccountInfoEntity();
		entity.setMoney(500500L);
		if (exist == null) {
			entity.setUserId("10001");
			accountInfoMapper.insert(entity);
		} else {
			entity.setId(exist.getId());
			accountInfoMapper.updateById(entity);
		}
		return "done";
	}

	@RequestMapping("debit")
	@Transactional
	public int debit(@RequestParam String userId, @RequestParam int money) {
		AccountInfoEntity exist = accountInfoMapper
				.selectOne(Wrappers.<AccountInfoEntity>lambdaQuery().eq(AccountInfoEntity::getUserId, userId));
		if (exist == null || exist.getMoney() < money) {
			throw new RuntimeException("账户不存在或余额不足");
		}

		AccountInfoEntity entity = new AccountInfoEntity();
		entity.setMoney(exist.getMoney() - money);
		entity.setId(exist.getId());
		return accountInfoMapper.updateById(entity);
	}
}
